package ${VIEWS_AppImplPackage};

import ${ViewRootPackage}.${entity}View;
import ${ViewRootPackage}.${entity}DetailView;
import ${ViewRootPackage}.${entity}Representation;
import ${VIEWS_QueryConditionPackage}.${entity}Condition;
import ${POPackage}.${entity}PO;
import ${MapperPackage}.${entity}Mapper;
import com.askj.integration.infrastructure.support.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.mapstruct.IterableMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * @author ${author!''}
 */
@Service
@AllArgsConstructor
public class Default${entity}Representation implements ${entity}Representation {

    private static final ${entity}ViewConverter CONVERTER = Mappers.getMapper(${entity}ViewConverter.class);

    private ${entity}Mapper mapper;


    @Override
    public PageResult<${entity}View> pageable(${entity}Condition condition) {
        LambdaQueryWrapper<${entity}PO> wrapper = Wrappers.lambdaQuery();

        wrapper.orderByDesc(${entity}PO::getCreatedTime);
        IPage<${entity}PO> page = mapper.selectPage(new Page<>(condition.getPage(), condition.getSize()), wrapper);
        PageResult<${entity}View> pageResult = new PageResult<${entity}View>().defaultOf(
                condition.getSize(),
                condition.getPage(),
                page.getTotal(),
                CONVERTER.toListViews(page.getRecords()));
        return pageResult;
    }


    @Override
    public ${entity}DetailView detail(String id) {
        ${entity}PO po = mapper.selectById(id);
        return CONVERTER.toDetailView(po);
    }


    @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
    interface ${entity}ViewConverter {
        /**
         * 转换为列表显示对象
         *
         * @param po
         * @return
         */
        @Named("toListView")
        ${entity}View toListView(${entity}PO po);


        @IterableMapping(qualifiedByName = "toListView")
        List<${entity}View> toListViews(List<${entity}PO> pos);

        /**
         * 转换为详情显示对象
         *
         * @param po
         * @return
         */
        @Named("toDetailView")
        ${entity}DetailView toDetailView(${entity}PO po);

    }
}
